<template>
  <div id="uploader" :class="{ active: isShow }">
    <img src="~@/assets/project/arrow.png" class="arrow" alt="" @click="isShow = !isShow">

    <h3>上传列表</h3>
    <uploader
      ref="uploader"
      :options="options"
      :auto-start="false"
      class="uploader-app"
      @file-added="onFileAdded"
      @file-success="onFileSuccess"
      @file-progress="onFileProgress"
      @file-Complete="onFileComplete"
      @complete="onComplete"
      @file-error="onFileError"
    >
      <!-- <uploader-unsupport /> -->
      <uploader-btn
        id="global-uploader-btn"
        ref="uploadBtn"
        :attrs="attrs"
      >选择文件
      </uploader-btn>
      <uploader-list/>
    </uploader>
  </div>
</template>

<script>
  import { fileAdd } from '@/api/file'
  import { folderJudge1, fileJudge1 } from './judge'

  export default {
    name: 'UploaderApp',
    components: {},
    props: {
      selectedNode: {
        type: Object,
        // 对象或数组默认值必须从一个工厂函数获取
        default: function() {
          return { id: '', name: '' }
        }
      }
    },
    data() {
      return {
        type: 'file',
        isShow: true,
        options: {
          target: '', // 目标上传 URL
          chunkSize: 10240 * 1024 * 1024, // 分块大小
          fileParameterName: 'file', // 上传文件时文件的参数名，默认file
          maxChunkRetries: 3, // 最大自动失败重试上传次数
          testChunks: false, // 是否开启服务器分片校验
          query: this.onQuery
        },
        attrs: {
          // 接受的文件类型，形如['.png', '.jpg', '.jpeg', '.gif', '.bmp'...] 这里我封装了一下
          accept: ['.png', '.jpg', '.jpeg', '.gif', '.bmp','.xls','.doc','.docx','.xls','.xlsx','.pdf']
        }
      }
    },
    computed: {
      uploader() {
        return this.$refs.uploader
      },
      uploadBtn() {
        return this.$refs.uploadBtn
      }
    },
    created() {
    },
    methods: {
      uploadFile(data) {
        this.type = 'file'
        console.log(this.uploadBtn.$refs.btn)
        this.uploadBtn.$refs.btn
          .querySelector('input')
          .removeAttribute('webkitdirectory')
        this.uploader.uploader.opts.target = this.ServerUrl + '/file/upload'
        this.uploadBtn.$refs.btn.click()
      },
      uploadFolder(data) {
        this.type = 'folder'
        this.uploadBtn.$refs.btn
          .querySelector('input')
          .setAttribute('webkitdirectory', 'webkitdirectory')
        this.uploader.uploader.opts.target = this.ServerUrl + '/folder/upload'
        this.uploadBtn.$refs.btn.click()
      },
      onFileSuccess(rootFile, file, response, chunk) {
        console.log(file)
      },
      onFileProgress(rootFile, file, chunk) {
        console.log(rootFile)
        console.log(file)
        console.log(chunk)
      },
      onFileError(rootFile, file, response, chunk) {
        console.log(file)
      },
      onFileComplete(rootFile) {
        console.log(rootFile)
        console.log('上传完成-------------onFileComplete')
      },
      onComplete() {
        console.log('上传完成')
        console.log()
        this.isShow = true
        if (this.type === 'file') {
          console.log('file')
          const data = this.$parent.$refs.tree.getCurrentNode()
          this.$parent.handleNodeClick(data)
        } else {
          this.$parent.folderTree()
          console.log('folder')
        }
      },
      async onFileAdded(file) {
        this.isShow = false

        // file.ignored = true
        console.log(file.webkitRelativePath)
        if (file.file.webkitRelativePath === '') {
          this.computeMD5(file)
        } else {
          const parentId = this.selectedNode.id
          const webkitRelativePath = file.relativePath
          const name = webkitRelativePath.split('/')[0]
          const is = await folderJudge1(parentId, name)
          is ? file.resume() : ''
          console.log(is)
        }
      },
      async computeMD5(file) {
        const parentId = this.selectedNode.id
        let is = false
        const name = file.name
        is = await fileJudge1(parentId, name)
        const md5 = is ? await this.fileAdd(name) : ''
        file.uniqueIdentifier = md5
        file.resume()
      },
      onQuery(File, Chunk, isTest) {
        let query = {}
        const folderId = this.selectedNode.id
        if (File.file.webkitRelativePath === '') {
          query = {
            chunks: 1,
            chunk: 1,
            size: File.size,
            fileSize: File.size,
            md5: File.uniqueIdentifier
          }
        } else {
          query = {
            projectId: sessionStorage.projectId,
            fileSize: File.size,
            fileName: File.name,
            filePath: File.file.webkitRelativePath,
            folderId
          }
        }

        return query
      },
      fileAdd(name) {
        const folderId = this.selectedNode.id
        return new Promise(function(resolve, reject) {
          fileAdd(folderId, name)
            .then(result => {
              const { msg } = result
              resolve(msg)
            })
            .catch(err => {
              console.log(err)
              reject(err)
            })
        })
      }
    }
  }
</script>
<style lang="scss">
  #uploader {
    position: fixed !important;
    bottom: 0;
    right: 0;
    width: 1000px;
    height: 300px;
    z-index: 999;
    background-color: #fff;
    transition: all 1s;
    box-shadow: 0 0 5px rgba($color: #eaeaea, $alpha: 1);
    border-radius: 8px 0 0 0;

    .uploader-app {
      height: 265px;
      border: 1px dashed #d9d9d9;
      overflow: auto
    }

    h3 {
      margin: 0;
      line-height: 45px;
      text-align: center;
    }

    #global-uploader-btn,
    .uploader-file-actions {
      display: none;
    }

    .arrow {
      font-size: 30px;
      position: absolute;
      left: -30px;
      cursor: pointer;
    }

    &.active {
      right: -1000px;

      .arrow {
        transform: rotate(180deg);
      }
    }
  }
</style>
